package com.golxen.framework.netty.session.agent;


import com.golxen.framework.PBPacket.PBPacket;
import com.golxen.framework.common.server.agent.AbstractDispatcher;
import com.golxen.framework.netty.NettyServices;
import com.golxen.utils.LogUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;

public class ServerClientHandler extends SimpleChannelInboundHandler<PBPacket> {

	private static Logger logger = LogUtil.COMMON;


	public ServerClientHandler() {

	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, PBPacket msg) throws Exception {
		AbstractDispatcher.dispatch(ctx, msg);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		logger.debug("连接断开 : " + ctx.channel().remoteAddress());
		ServerClientGroup client = (ServerClientGroup) ctx.channel().attr(NettyServices.LINKED_CLIENT).get();
		if (client != null) {
			ServerClientReConnectHelper.tryConnect(client, 10);
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		logger.debug("连接异常 : " + ctx.channel().remoteAddress() + " error : " + cause);

		ServerClientGroup client = (ServerClientGroup) ctx.channel().attr(NettyServices.LINKED_CLIENT).get();
		if (client != null) {
			logger.error("msg : " + client.toString(), cause);
		}

		ctx.close();
	}

}
